package cn.gailvlun.gll.widget

import android.content.Context
import android.util.AttributeSet
import android.widget.ImageView
import cn.gailvlun.gll.R


enum class PlayState {
    READY_TO_PLAY,
    PLAYING
}

interface OnPlayListener {
    fun onPlay(pb: PlayButton, state: PlayState)
}

class PlayButton: ImageView {

    var mOnPlayListener: OnPlayListener? = null
    var mState = PlayState.READY_TO_PLAY

    constructor(context: Context?) : this(context, null)
    constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        setImageResource(R.drawable.ic_play_button_play)
        setOnClickListener {
            when (mState) {
                PlayState.READY_TO_PLAY -> {
                    setState(PlayState.PLAYING)
                }
                PlayState.PLAYING -> {
                    setState(PlayState.READY_TO_PLAY)
                }
            }
        }
    }

    fun stop() {
        setState(PlayState.READY_TO_PLAY, false)
    }

    private fun setState(state: PlayState, trigger: Boolean = true) {
        mState = state
        if (trigger) {
            mOnPlayListener?.onPlay(this, mState)
        }
        when (mState) {
            PlayState.READY_TO_PLAY -> {
                setImageResource(R.drawable.ic_play_button_play)
            }
            PlayState.PLAYING -> {
                setImageResource(R.drawable.ic_share_playing)

            }
        }
    }
}